<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('departments', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('parent_id')->nullable()->comment('父部门ID');
            $table->string('name', 100)->comment('部门名称');
            $table->string('code', 50)->unique()->comment('部门编码');
            $table->text('description')->nullable()->comment('部门描述');
            $table->unsignedBigInteger('manager_id')->nullable()->comment('部门负责人ID');
            $table->string('phone', 20)->nullable()->comment('部门电话');
            $table->string('email', 100)->nullable()->comment('部门邮箱');
            $table->string('address')->nullable()->comment('部门地址');
            $table->enum('status', ['active', 'inactive'])->default('active')->comment('部门状态');
            $table->integer('sort_order')->default(0)->comment('排序权重');
            $table->json('settings')->nullable()->comment('部门设置');
            $table->timestamps();
            
            // 外键约束
            $table->foreign('parent_id')->references('id')->on('departments')->onDelete('cascade');
            $table->foreign('manager_id')->references('id')->on('users')->onDelete('set null');
            
            // 索引
            $table->index(['parent_id', 'status']);
            $table->index(['code', 'status']);
            $table->index(['name', 'status']);
            $table->index('sort_order');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('departments');
    }
};
